#include "formatsettings.h"
#include "ui_formatsettings.h"
#include <QTest>

FormatSettings::FormatSettings(QWidget *parent) :
    SettingsMenuItem(parent),
    ui(new Ui::FormatSettings)
{
    ui->setupUi(this);
    initializeButtons();
    recentlyAdded=new QList<QWidget *>();
}

FormatSettings::~FormatSettings()
{
    delete ui;
}

void FormatSettings::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void FormatSettings::initializeButtons() {
   QSqlQueryModel * model= Querier::getModel("SELECT * FROM Extensions ORDER BY fileType ASC");
    for(int i=0; i<model->rowCount(); i++) {
        QSqlRecord record=model->record(i);
        if(record.value("fileType").toString()=="Video") {
            if(ui->videoExtensions->count()==0) {
                photoDialog=new KeyDialog(this);
                addPhotoExtButton =new Button(QIcon(""),"Add Extension",this,photoDialog);
                ui->photoAddExtension->addWidget(addPhotoExtButton);
                addDialog(addPhotoExtButton,photoDialog);
            }
            QWidget * currentRow=new QWidget();
            currentRow->setLayout(new QHBoxLayout());
            currentRow->layout()->addWidget(new QLabel(record.value("extension").toString()));
            Button * button=new Button(QIcon(""),"Remove",this,currentRow);
            currentRow->layout()->addWidget(button);
            addRow(button);
            ui->videoExtensions->addWidget(currentRow);
        }
        else if(record.value("fileType").toString()=="Music") {
            QWidget * currentRow=new QWidget();
            currentRow->setLayout(new QHBoxLayout());
            currentRow->layout()->addWidget(new QLabel(record.value("extension").toString()));
            Button * button=new Button(QIcon(""),"Remove",this,currentRow);
            currentRow->layout()->addWidget(button);
            addRow(button);
            ui->musicExtensions->addWidget(currentRow);
        }
        else {
            if(ui->photoExtensions->children().count()==0) {
                musicDialog=new KeyDialog(this);
                addMusicExtButton =new Button(QIcon(""),"Add Extension",this,musicDialog);
                ui->musicAddExtension->addWidget(addMusicExtButton);
                addDialog(addMusicExtButton,musicDialog);
            }
            QWidget * currentRow=new QWidget();
            currentRow->setLayout(new QHBoxLayout());
            currentRow->layout()->addWidget(new QLabel(record.value("extension").toString()));
            Button * button=new Button(QIcon(""),"Remove",this,currentRow);
            currentRow->layout()->addWidget(button);
            addRow(button);
            ui->photoExtensions->addWidget(currentRow);
        }
    }
    videoDialog=new KeyDialog(this);
    addVideoExtButton =new Button(QIcon(""),"Add Extension",this,videoDialog);
    ui->videoAddExtension->addWidget(addVideoExtButton);
    addDialog(addVideoExtButton,videoDialog);

    QHBoxLayout * horizontalLayout=new QHBoxLayout();
    QList<Button *> * list=new QList<Button *>();
    saveButton = new Button(QIcon(""),"Save",this,NULL);
    horizontalLayout->addWidget(saveButton);
    list->append(saveButton);
    cancelButton = new Button(QIcon(""),"Cancel",this);
    horizontalLayout->addWidget(cancelButton);
    list->append(cancelButton);
    addRow(list);
    layout()->addItem(horizontalLayout);
}

void FormatSettings::addDialog(Button *button, KeyDialog *dialog) {
    dialog->setWindowFlags(Qt::Dialog|Qt::FramelessWindowHint |Qt::WindowStaysOnTopHint);
    dialog->hide();
    dialog->setLabel("Please enter the extension to add");
    connect(dialog,SIGNAL(okSelected(KeyDialog*)),this,SLOT(update(KeyDialog *)));
    connect(dialog,SIGNAL(cancelSelected()),this,SLOT(reshowComponents()));
    addRow(button);
}

void FormatSettings::buttonSelected() {
    if(getCurrentButton()==saveButton) {
        save();
    } else if(getCurrentButton()==cancelButton) {
        cancel();
    }
    else {
        KeyDialog * dialog=qobject_cast<KeyDialog *>(getCurrentButton()->getItem());
        if (dialog) {
            deactivate();
            dialog->show();
        } else {
            QWidget * widget=qobject_cast<QWidget *>(getCurrentButton()->getItem());
            qDebug() <<widget<<" "<<getCurrentButton()->getItem();
            if(widget) {
                removeButton(getCurrentButton());
                widget->hide();
            }
        }
    }
}

void FormatSettings::reshowComponents() {
    grabKeyboard();
    activate();
}

void FormatSettings::save() {
    //delete hidden ones
    for(int i=0; i<children().size(); i++) {
        QWidget * widget=qobject_cast<QWidget *>(children().at(i));
        if(widget) {
            qDebug()<<"this is a "<<widget;
            if(!widget->isVisible()) {
                for(int j=0; j<widget->children().size(); j++) {
                    QLabel * label = qobject_cast<QLabel *>(widget->children().at(j));
                    qDebug() <<"is the child a label "<<label;
                    if(label) {
                        Querier::getResult("DELETE FROM Extensions WHERE extension='"+label->text()+"'");
                        qDebug()<<"DELETE FROM Extensions WHERE extension='"+label->text()+"'";
                    }
                }
            }
        }
    }

    //add new ones which aren't hidden


    foreach(QWidget * widget, *recentlyAdded) {
        if(widget) {
            qDebug()<<"this is a "<<widget;
            if(widget->isVisible()) {
                for(int j=0; j<widget->children().size(); j++) {
                    QLabel * label = qobject_cast<QLabel *>(widget->children().at(j));
                    QString type="Music";
                    if(ui->photoExtensions->indexOf(widget)!=-1) {
                        type="Photo";
                    } else if(ui->videoExtensions->indexOf(widget)!=-1) {
                        type="Video";
                    }
                    if(label) {
                        qDebug() <<"INSERT INTO Extensions (fileType,extension) VALUES ('"+type+"','"+label->text()+"')";
                        Querier::getResult("INSERT INTO Extensions (fileType,extension) VALUES ('"+type+"','"+label->text()+"')");
                    }
                }
            }
        }


    }

    emit completed();
}

void FormatSettings::cancel() {
    qDebug() <<"cancelled";
    for(int i=0; i<recentlyAdded->size();) {
        QWidget * widget=recentlyAdded->first();
        recentlyAdded->removeFirst();
        widget->hide();
        Button * button=qobject_cast<Button *>(widget->children().at(1));
        removeButton(button);
    }
    emit completed();
}

void FormatSettings::update(KeyDialog * dialog) {
    activate();
    grabKeyboard();
    QWidget * currentRow=new QWidget();
    currentRow->setLayout(new QHBoxLayout());
    currentRow->layout()->addWidget(new QLabel(dialog->getText()));
    Button * button=new Button(QIcon(""),"Remove",this,currentRow);
    currentRow->layout()->addWidget(button);
    recentlyAdded->append(currentRow);
    if(dialog==videoDialog) {
        addButtonBefore(button,addVideoExtButton);
        ui->videoExtensions->addWidget(currentRow);
    }
    else if(dialog==photoDialog) {
        addButtonBefore(button,addPhotoExtButton);
        ui->photoExtensions->addWidget(currentRow);
    }
    else {
        addButtonBefore(button,addMusicExtButton);
        ui->musicExtensions->addWidget(currentRow);
    }
    dialog->clearText();
}

void FormatSettings::test() {

}

void FormatSettings::saveTest() {
    QTest::mouseMove(addVideoExtButton);
    QTest::qWait(500);
    emit buttonEntered(addVideoExtButton);
    QTest::mouseClick( addVideoExtButton, Qt::LeftButton);
    KeyDialog * dialog=(KeyDialog *)addVideoExtButton->getItem();
    QTest::qWait(1000);
    QTest::keyClicks(dialog,".mpg");
    QTest::qWait(1000);
    QTest::mouseClick( dialog->getOkButton(), Qt::LeftButton);
    QTest::qWait(2000);
    QTest::mouseMove(saveButton);
    emit buttonEntered(saveButton);
    QTest::qWait(500);
    QTest::mouseClick( saveButton, Qt::LeftButton);
}

void FormatSettings::assertSaved() {
    QSqlQuery record=Querier::getResult("SELECT * FROM extensions WHERE extension='.mpg'");
    if(record.size()==0) {
        QFAIL("Added extension not found. Error in Format Settings.");
    }


    for(int i=0; i<children().size(); i++) {
        QWidget * widget=qobject_cast<QWidget *>(children().at(i));
        if(widget) {
            for(int j=0; j<widget->children().size(); j++) {
                QLabel * label=qobject_cast<QLabel *>(widget->children().at(j));
                if(label) {
                    qDebug()<<label<<" "<<label->text();
                    if(label->text()==".mpg") {
                        Button * button=qobject_cast<Button *>(widget->children().at(j+1));
                        if(button) {
                            qDebug()<<widget->pos()<<" "<<button->pos();
                            QPoint point(widget->x()+button->x()+20,widget->y()+button->y()+20);
                            //qDebug() <<point;
                            QTest::mouseMove(button);
                            emit buttonEntered(button);
                            QTest::qWait(2000);
                            QTest::mouseClick( button, Qt::LeftButton);
                            QTest::qWait(1000);
                            QTest::mouseMove(saveButton);
                            emit buttonEntered(saveButton);
                            QTest::qWait(500);
                            QTest::mouseClick( saveButton, Qt::LeftButton);
                            QTest::qWait(1000);
                            return;
                        }
                    }
                }
            }
        }
    }
    QFAIL(".mpg extension not found. Saving formats failed.");
}

void FormatSettings::cancelTest() {
    QTest::mouseMove(addVideoExtButton);
    emit buttonEntered(addVideoExtButton);
    QTest::qWait(500);
    QTest::mouseClick( addVideoExtButton, Qt::LeftButton);
    KeyDialog * dialog=(KeyDialog *)addVideoExtButton->getItem();
    QTest::qWait(1000);
    QTest::keyClicks(dialog,".mpg");
    QTest::qWait(1000);
    QTest::mouseClick( dialog->getOkButton(), Qt::LeftButton);
    QTest::qWait(2000);
    QTest::mouseMove(cancelButton);
    emit buttonEntered(cancelButton);
    QTest::qWait(500);
    QTest::mouseClick( cancelButton, Qt::LeftButton);
    QTest::qWait(1000);
}

void FormatSettings::assertCancelled() {
    for(int i=0; i<children().size(); i++) {
        QWidget * widget=qobject_cast<QWidget *>(children().at(i));
        if(widget) {
            for(int j=0; j<widget->children().size(); j++) {
                QLabel * label=qobject_cast<QLabel *>(widget->children().at(j));
                if(label) {
                    qDebug()<<label<<" "<<label->text();
                    if(label->text()==".mpg"&&label->isVisible()) {
                        QFAIL("Cancelling did not work. Format Settings failure");
                    }
                }
            }
        }
    }
}
